import React, {useEffect, useState} from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Image, Upload,Form } from 'antd';
const getBase64 = (file) =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });



export default function UploadImg({setImageBase64 ,imageBase64 ,form}) {
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [fileList, setFileList] = useState([
    ]);
    const [abc,setABC]=useState(false);
    const token=localStorage.getItem('token');
    const headers= {
        token: token, // 将令牌添加到请求头中
    };
    const handlePreview = async (file) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        setPreviewImage(file.url || file.preview);
        setPreviewOpen(true);
    };
    useEffect(()=>{
        if(fileList.length > 0) {
            console.log(fileList);
            // 延迟一段时间再获取缩略图
            setTimeout(() => {
                if (fileList[0].thumbUrl) {
                    setImageBase64(fileList[0].thumbUrl);
                    let img_data_without_prefix = fileList[0].thumbUrl.replace("data:image/png;base64,", "")
                    form.setFieldsValue({
                        verificationImage:img_data_without_prefix ,
                    });
                    console.log(img_data_without_prefix);
                }
            }, 5000); // 在这里设置适当的延迟时间

        }
    }, [fileList]);
    const handleChange = ({ fileList: newFileList }) => setFileList(newFileList);
    const uploadButton = (
        <button
            style={{
                border: 0,
                background: 'none',
            }}
            type="button"
        >
            <PlusOutlined />
            <div
                style={{
                    marginTop: 8,
                }}
            >
                Upload
            </div>
        </button>
    );

  return (
      <>
      <Upload
          action="http://localhost:8080/auth/avatar"
          listType="picture-card"
          fileList={fileList}
          onPreview={handlePreview}
          onChange={handleChange}
          headers={headers}
      >
          {fileList.length >= 8 ? null : uploadButton}
      </Upload>
    {previewImage && (
        <Image
            wrapperStyle={{
                display: 'none',
            }}
            preview={{
                visible: previewOpen,
                onVisibleChange: (visible) => setPreviewOpen(visible),
                afterOpenChange: (visible) => !visible && setPreviewImage(''),
            }}
            src={previewImage}
        />
    )}
</>
  );
}
